import { createRouter, createWebHistory, type LocationQueryValue } from 'vue-router'
import i18n, { loadLanguageAsync, supportLanguages } from '@/locales/i18n'
import { useAppConfigStore } from '@/stores'
import { defineAsyncComponent, h } from 'vue'
import Loading from '@/views/loading/loading.vue'

function lazyLoad(component_name: string, params = {}) {
  return {
    render() {
      const async_component = defineAsyncComponent({
        loader: () => import(`../views/${component_name}.vue`),
        loadingComponent: Loading,
        ...params
      })
      return h(async_component)
    }
  }
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition
    }
    return { top: 0 }
  },
  routes: [
    {
      path: '/',
      name: 'index',
      component: () => import(`../views/index/index.vue`),
      meta: {
        title: 'AppList'
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  // , theme:LocationQueryValue
  const lang: LocationQueryValue | LocationQueryValue[] = to.query.lang
  const appConfigStore = useAppConfigStore()
  if (lang != null && supportLanguages.includes((lang || '').toString())) {
    if (appConfigStore.$state.lang !== lang.toString()) {
      // 路由带参数 不用 语言才进行 加载 语言文本
      return loadLanguageAsync(lang.toString()).then(() => {
        return next()
      })
    }
  }
  return loadLanguageAsync(appConfigStore.$state.lang.toString()).then(() => {
    return next()
  })
})

router.afterEach((to, from) => {
  console.warn('from ::: ', from)
  console.warn('to ::: ', to)
  document.title = (to.meta.title ?? '').toString()
})

export default router
